package ac.zlf.core.util.security;

import java.io.IOException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import net.iharder.Base64;

public class Signatures {
    private static final String ENCODING = "UTF-8";
    private static final String MAC_NAME = "HmacSHA1";

    public static String generateSignature(URL url, String method, String signatureKey)
            throws IOException {
        byte[] keyBytes = Base64.decode(signatureKey);
        SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(key);
            String message = String.format("%s+%s+%s+%s", new Object[]{method, url.getProtocol(), url.getPath(), url.getQuery()});
            mac.update(message.getBytes("UTF-8"));
            return Base64.encodeBytes(mac.doFinal());
        } catch (NoSuchAlgorithmException e) {
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String generateSignature(String currentTime, String nonce, String secretToken, String signatureKey) {
        return Digests.sha1(String.format("%s.%s.%s.%s", new Object[]{currentTime, nonce, secretToken, signatureKey}));
    }
}